import os
import requests
import py7zr

'''
AUTHOR = "affggh"
VERSION = "0.1"

Updater for this tool
'''

updateSource = "https://viqoo.mouzei.repl.co/d/onedrive"
currentVersion = "1.0.0"

def checkCurrentVersion():
    ver = "1.0.0"
    if os.access("bin/viqoo_config.bat", os.F_OK):
        with open("bin/viqoo_config.bat", 'r') as f:
            for line in f:
                if not line.find("program_ver") == -1:
                    ver = line.split('=')[1].lower().strip('v')
    return ver

def checkOnlineVersion():
    buf = requests.get(updateSource+"/update.txt").content.decode('gb2312')
    info = {}
    for i in buf.splitlines():
        if i.startswith("工具箱"):
            if len(i.split(' ')) > 3:
                info['ver'] = i.split(' ')[1].lower().strip('v')
                info['date'] =  i.split(' ')[2]
                info['new'] = i.split(' ')[3]
    return info

def compareCurrentVersionAndOnlineVersion(info, currentVersion):
    if currentVersion:
        cver = str(currentVersion).strip("\n").split(".")
        over = str(info['ver']).strip("\n").split(".")
        # print("c=%s o=%s" %(cver, over))
        if len(cver) == len(over):
            for i in range(len(over)):
                if int(over[i])>int(cver[i]):
                    # print("发现更新")
                    return True
        # print("没有更新")
        return False

def downloadFile(url, fileToSave):
    def progress(now, total):
        return int((now/total)*100)
    file = fileToSave
    chunk_size = 512
    print("下载文件")
    r = requests.get(url, stream=True)
    total_size = int(r.headers['content-length'])
    now = 0
    with open(file, 'wb') as f:
        for chunk in r.iter_content(chunk_size=chunk_size):
            if chunk:
                before = now
                f.write(chunk)
                now += chunk_size
                if now > before:
                    print("下载进度 [%s/100]" %progress(now, total_size), end='\r')
    print("下载完成")

def getUpdate():
    url = updateSource+"/viQOO.7z"
    downloadFile(url, "viQOO.7z")

def decompressFile(file):
    with py7zr.SevenZipFile(file, mode='r') as z:
        # print("解压文件")
        z.extractall()

def getModelSupportList():
    buf = requests.get(updateSource+"/model.txt").content.decode('gb2312')
    info = []
    for i in buf.splitlines():
        if i.startswith("【"):
            if len(i.split(' ')) > 1:
                info.append(i.split(' ')[1])
    return info

def selfVersionCheckout(cversion):
    url = "https://gitee.com/affggh/viqoo/raw/master/viQoo.py"
    buf = requests.get(url).content.decode('utf-8')
    pyversion = "1.0.0"
    for i in buf.splitlines():
        if i.startswith("VERSION"):
            pyversion = i.split('=')[1].replace('"', '').lstrip(" ").split(' ')[2]
            info = { 'ver' : pyversion }
            return compareCurrentVersionAndOnlineVersion(info, cversion)
    else:
        return False

if __name__ == '__main__':
    import time
    start = time.time()
    #info = checkOnlineVersion()
    #currentVersion = checkCurrentVersion()
    #if compareCurrentVersionAndOnlineVersion(info):
    #    getUpdate()
    #    decompressFile("viQOO.7z")

    #print(getModelSupportList())
    # print(selfVersionCheckout(cversion="1.0.0"))
    end_time = time.time()
    print("tooks %.2f" %(end_time-start))